package com.gitee.qdbp.general.system.biz.personnel.convert;

import java.util.ArrayList;
import java.util.List;
import org.springframework.core.convert.converter.Converter;
import com.gitee.qdbp.general.system.api.personnel.convert.IUserSourceConverter;
import com.gitee.qdbp.general.system.enums.IUserSource;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 用户来源转换类<br>
 * 将用户来源转换为指定枚举类
 *
 * @author zhaohuihua
 * @version 180404
 */
public class UserSourceConverter<E extends Enum<E>> implements IUserSourceConverter, Converter<String, IUserSource> {

    private List<IUserSource> types;
    private IUserSource defaults;
    private Class<E> clazz;

    /** 构造函数, 指定枚举类的路径和用户来源默认值 **/
    public UserSourceConverter(Class<E> type, String defaults) {
        VerifyTools.requireNotBlank(type, "type");
        VerifyTools.requireNotBlank(type, "defaults");

        this.clazz = type;

        // 检查枚举类
        if (!IUserSource.class.isAssignableFrom(type)) {
            throw new IllegalArgumentException(type.getSimpleName() + " not instance of IUserSource.");
        }

        // 初始化枚举项
        E[] enums = type.getEnumConstants();
        if (enums == null) {
            throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
        }
        this.types = new ArrayList<>();
        for (E e : enums) {
            types.add((IUserSource) e);
        }

        // 解析用户来源默认值
        this.defaults = convert(defaults);
        if (this.defaults == null) {
            String msg = "default value [" + defaults + "] has not in " + type.getSimpleName() + ".values()";
            throw new IllegalArgumentException(msg);
        }

    }

    /** 将字符串转换为用户来源枚举类, 如果不在枚举范围内则返回null **/
    @Override
    public IUserSource convert(String type) {
        if (VerifyTools.isNotBlank(type)) {
            for (IUserSource i : types) {
                if (i.name().equals(type) || String.valueOf(i.ordinal()).equals(type)) {
                    return i;
                }
            }
        }
        return null;
    }

    /** 获取用户来源默认值 **/
    @Override
    public IUserSource getDefaults() {
        return defaults;
    }

    /** 获取用户来源默认值 **/
    public Class<E> getEnumType() {
        return clazz;
    }
}
